# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:25
# File     : __init__.py.py
# Project  : codebuddy_craft
# Desc     :

# backend/database/__init__.py
"""
数据库模块

包含数据库初始化、连接管理和基础数据设置
"""

# import asyncio
# from sqlalchemy import text
# from typing import Dict, Any
#
# from .connection import (
#     create_database_engine,
#     test_database_connection,
#     get_async_session,
#     close_database,
#     Base,
#     engine
# )
# from backend.utils.logger import logger
#
#
# async def init_db():
#     """初始化数据库连接和表结构"""
#
#     try:
#         logger.info("🚀 开始初始化数据库...")
#
#         # 1. 创建数据库引擎
#         await create_database_engine()
#
#         # 2. 测试数据库连接
#         if not await test_database_connection():
#             raise Exception("数据库连接测试失败")
#
#         # 3. 创建所有表
#         await create_all_tables()
#
#         # 4. 初始化基础数据
#         await init_base_data()
#
#         logger.info("✅ 数据库初始化完成")
#
#     except Exception as e:
#         logger.error(f"❌ 数据库初始化失败: {str(e)}")
#         raise
#
#
# async def create_all_tables():
#     """创建所有数据库表"""
#     try:
#         logger.info("📋 开始创建数据库表...")
#
#         # 导入所有模型以确保它们被注册
#         from backend.models import (
#             user, project, file
#         )
#
#         async with engine.begin() as conn:
#             # 创建所有表
#             await conn.run_sync(Base.metadata.create_all)
#
#         logger.info("✅ 数据库表创建完成")
#
#     except Exception as e:
#         logger.error(f"❌ 创建数据库表失败: {str(e)}")
#         raise
#
#
# async def init_base_data():
#     """初始化基础数据"""
#     try:
#         logger.info("📝 开始初始化基础数据...")
#
#         async with get_async_session() as db:
#             # 检查是否需要初始化数据
#             from backend.models.user import User
#             from sqlalchemy import select
#
#             # 检查是否已有管理员用户
#             result = await db.execute(
#                 select(User).where(User.is_superuser == True)
#             )
#             admin_user = result.scalar_one_or_none()
#
#             if not admin_user:
#                 # 创建默认管理员用户
#                 await create_default_admin(db)
#
#             # 初始化其他基础数据
#             await init_default_templates(db)
#
#         logger.info("✅ 基础数据初始化完成")
#
#     except Exception as e:
#         logger.error(f"❌ 基础数据初始化失败: {str(e)}")
#         # 基础数据初始化失败不应该阻止应用启动
#         pass
#
#
# async def create_default_admin(db):
#     """创建默认管理员用户"""
#     try:
#         from backend.models.user import User
#         from backend.utils.security import get_password_hash
#         import uuid
#
#         admin_user = User(
#             id=str(uuid.uuid4()),
#             username="admin",
#             email="admin@codebuddy.com",
#             hashed_password=get_password_hash("admin123"),
#             full_name="系统管理员",
#             is_active=True,
#             is_superuser=True,
#             is_verified=True
#         )
#
#         db.add(admin_user)
#         await db.commit()
#         await db.refresh(admin_user)
#
#         logger.info("✅ 默认管理员用户创建成功 (用户名: admin, 密码: admin123)")
#
#     except Exception as e:
#         logger.error(f"❌ 创建默认管理员失败: {str(e)}")
#         await db.rollback()
